import axios from 'axios'
import router from '../router/index'
// import jwt_decode from 'jwt-decode' // 导入jwt_decode库

const BASE_URL = 'http://localhost:3000'
axios.defaults.headers.post['Content-Type'] = 'application/json'

//请求拦截
axios.interceptors.request.use((config) => {
  // interceptors 中文意思 拦截器
  let jwtToken = window.localStorage.getItem('jwtToken') || ''
  // 设置统一的请求头
  if (jwtToken) {
    config.headers.Authorization = jwtToken
  }
  return config
})


// 响应拦截
axios.interceptors.response.use((res) => {
  if (res.data.code !== 0) {
    return Promise.reject(res.data.err)
  }
  return res
},

  (error) => {
    if (error.response.status >= 400 && error.response.status <= 500) {
      // console.log(1);
      router.push('/login')
    }
    return Promise.reject(error.response.data, error)
  }
)

export function post(url, body) {
  return axios.post(BASE_URL + url, body)
}

export function get(url, body) {
  return axios.get(BASE_URL + url, body)
}



// // 解析token并存储用户信息
// let jwtToken = window.localStorage.getItem('jwtToken')
// if (jwtToken) {
//   const jwt_decode = require('jwt-decode'); // Use require to import jwt-decode
//   const decodedToken = jwt_decode(jwtToken)
//  // 将解析出的用户信息存储在state中
//   this.$store.commit('setUser', decodedToken)
// }